package com.tadpole.music.view.fragment.home;


import android.content.Intent;

import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.listener.LockClickListener;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.GSYVideoType;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;
import com.tadpole.music.R;
import com.tadpole.music.bean.home.HomeVideoBean;
import com.tadpole.music.config.Constant;
import com.tadpole.music.iView.home.HomeVideoIView;
import com.tadpole.music.presenter.home.HomeVideoPresenter;
import com.tadpole.music.utils.Mutils;
import com.tadpole.music.utils.NoDoubleClickListener;
import com.tadpole.music.utils.SpUtil;
import com.tadpole.music.utils.ToastUtils;
import com.tadpole.music.view.activity.home.OnlineExercisesActivity;
import com.tadpole.music.view.activity.login.LoginActivity;
import com.tadpole.music.view.activity.me.MemberCenterActivity;
import com.tadpole.music.view.activity.study.AnswerStatisticsActivity;
import com.tadpole.music.view.activity.study.MyErrorTopicActivity;
import com.tadpole.music.view.activity.study.MyExamsActivity;
import com.tadpole.music.view.event.StopPlayEvent;
import com.tadpole.music.view.fragment.base.BaseFragment;
import com.tadpole.music.view.widget.LandLayoutVideo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;


/**
 * Created By 孙岩
 * on 2020/11/25
 */
public class BannerFragment extends BaseFragment implements HomeVideoIView {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";
    private String mParam1;
    private String mParam2;
    private String mParam3;
    //视频
    private FrameLayout flVideo;
    //视频控件
    private LandLayoutVideo detailPlayer;
    //图片控件
    private FrameLayout flImage;
    //图片
    private ImageView ivImage;
    //是否正在播放
    private boolean isPlay = true;
    private ImageView ivStop;
    private OrientationUtils orientationUtils;

    //获取首页视频
    private HomeVideoPresenter homeVideoPresenter;
    public static BannerFragment newInstance(String param1, String param2, String param3) {
        BannerFragment fragment = new BannerFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        args.putString(ARG_PARAM3, param3);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_banner;
    }

    @Override
    protected void initAllMembersView(Bundle savedInstanceState) {
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
            mParam3 = getArguments().getString(ARG_PARAM3);
        }
        //注册
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected void initView(View mRootView) {
        flVideo = mRootView.findViewById(R.id.flVideo);
        ivStop = mRootView.findViewById(R.id.ivStop);
        detailPlayer = mRootView.findViewById(R.id.plVideoView);
        flImage = mRootView.findViewById(R.id.flImage);
        ivImage = mRootView.findViewById(R.id.ivImage);

        homeVideoPresenter = new HomeVideoPresenter();
        homeVideoPresenter.attachView(this);


        ivStop.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if(isPlay){
                    detailPlayer.setPasue(true);
                    isPlay = false;
                    ivStop.setImageResource(R.mipmap.start_play_icon);
                }else{
                    detailPlayer.setPasue(false);
                    isPlay = true;
                    ivStop.setImageResource(R.mipmap.stop_play_icon);
                }
            }
        });


        if (mParam1.equals("0")) {
            //第一个是视频
            homeVideoPresenter.getVideo();
        } else {
            //之后是轮播图
            showElse();
        }
    }

    private void showElse(){
        flVideo.setVisibility(View.GONE);
        flImage.setVisibility(View.VISIBLE);
        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.mipmap.app_icon)
                .error(R.mipmap.app_icon)
                .priority(Priority.HIGH)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(getActivity()).load(Constant.IMAGE_HEAD + mParam2).apply(requestOptions).into(ivImage);

        ivImage.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (SpUtil.getInstance(getActivity()).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    } else {
                        switch (mParam3) {
                            case "1": {//会员中心
                                Intent intent = new Intent(getActivity(), MemberCenterActivity.class);
                                intent.putExtra("flag", "2");
                                startActivity(intent);
                                break;
                            }
                            case "2": {//在线套题
                                Intent intent = new Intent(getActivity(), OnlineExercisesActivity.class);
                                intent.putExtra("college_id", 1);
                                intent.putExtra("name", "中央音乐学院");
                                startActivity(intent);
                                break;
                            }
                            case "3": {//我的考试
                                Intent intent = new Intent(getActivity(), MyExamsActivity.class);
                                startActivity(intent);
                                break;
                            }
                            case "4": {//我的错题
                                Intent intent = new Intent(getActivity(), MyErrorTopicActivity.class);
                                startActivity(intent);
                                break;
                            }
                            case "5": {//答题统计
                                Intent intent = new Intent(getActivity(), AnswerStatisticsActivity.class);
                                startActivity(intent);
                                break;
                            }
                        }
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        getCurPlay().onVideoPause();
        detailPlayer.setPasue(true);
        isPlay = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getCurPlay().onVideoPause();
        getCurPlay().release();
        EventBus.getDefault().unregister(this);//取消注册
        if (orientationUtils != null) {
            orientationUtils.releaseListener();
        }
    }

    //播放的东西
    private void playVideo(String url) {
        resolveNormalVideoUI();
        //外部辅助的旋转，帮助全屏
        orientationUtils = new OrientationUtils(getActivity(), detailPlayer);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);

        GSYVideoOptionBuilder gsyVideoOption = new GSYVideoOptionBuilder();

        gsyVideoOption
                .setIsTouchWiget(true)
                .setRotateViewAuto(false)
                .setLockLand(false)
                .setAutoFullWithSize(false)
                .setShowFullAnimation(false)
                .setNeedLockFull(false)
                .setLooping(true)
                .setUrl(url)
                .setCacheWithPlay(false)
//                .setVideoAllCallBack(new GSYSampleCallBack() {
//                    @Override
//                    public void onPrepared(String url, Object... objects) {
//                        Debuger.printfError("***** onPrepared **** " + objects[0]);
//                        Debuger.printfError("***** onPrepared **** " + objects[1]);
//                        super.onPrepared(url, objects);
//                        //开始播放了才能旋转和全屏
//                        orientationUtils.setEnable(true);
//                    }
//
//                    @Override
//                    public void onEnterFullscreen(String url, Object... objects) {
//                        super.onEnterFullscreen(url, objects);
//                        Debuger.printfError("***** onEnterFullscreen **** " + objects[0]);//title
//                        Debuger.printfError("***** onEnterFullscreen **** " + objects[1]);//当前全屏player
//                    }
//
//                    @Override
//                    public void onAutoComplete(String url, Object... objects) {
//                        super.onAutoComplete(url, objects);
//                    }
//
//                    @Override
//                    public void onClickStartError(String url, Object... objects) {
//                        super.onClickStartError(url, objects);
//                    }
//
//                    @Override
//                    public void onQuitFullscreen(String url, Object... objects) {
//                        super.onQuitFullscreen(url, objects);
//                        Debuger.printfError("***** onQuitFullscreen **** " + objects[0]);//title
//                        Debuger.printfError("***** onQuitFullscreen **** " + objects[1]);//当前非全屏player
//                        if (orientationUtils != null) {
//                            orientationUtils.backToProtVideo();
//                        }
//                    }
//                })
//                .setLockClickListener(new LockClickListener() {
//                    @Override
//                    public void onClick(View view, boolean lock) {
//                        if (orientationUtils != null) {
//                            //配合下方的onConfigurationChanged
//                            orientationUtils.setEnable(!lock);
//                        }
//                    }
//                })
//                .setGSYVideoProgressListener(new GSYVideoProgressListener() {
//                    @Override
//                    public void onProgress(int progress, int secProgress, int currentPosition, int duration) {
//                        Debuger.printfLog(" progress " + progress + " secProgress " + secProgress + " currentPosition " + currentPosition + " duration " + duration);
//                    }
//                })

                .build(detailPlayer);


        detailPlayer.setPasue(true);
        isPlay = false;
        detailPlayer.startPlayLogic();

        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL);

        detailPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //直接横屏
                orientationUtils.resolveByClick();

                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                detailPlayer.startWindowFullscreen(getActivity(), true, true);
            }
        });

    }

    private void resolveNormalVideoUI() {
        //增加title
        detailPlayer.getTitleTextView().setVisibility(View.GONE);
        detailPlayer.getBackButton().setVisibility(View.GONE);
    }

    public GSYVideoPlayer getCurPlay() {
        if (detailPlayer.getFullWindowPlayer() != null) {
            return detailPlayer.getFullWindowPlayer();
        }
        return detailPlayer;
    }

    //停止播放
    @Subscribe
    public void onStop(StopPlayEvent event) {
        getCurPlay().onVideoPause();
    }

    @Override
    public void showVideo(HomeVideoBean.DataBean bean) {
        flVideo.setVisibility(View.VISIBLE);
        flImage.setVisibility(View.GONE);
        playVideo(bean.getVideo());
    }
}
